package com.lw.leetcode.back.b;

/**
 * Created with IntelliJ IDEA.
 * LCS 03. 主题空间
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/12 21:16
 */
public class LargestArea {


    public static void main(String[] args) {
        LargestArea test = new LargestArea();

        // 1
//        String[] arr = {"110", "231", "221"};

        // 3
        String[] arr = {"11111100000", "21243101111", "21224101221", "11111101111"};

        int i = test.largestArea(arr);
        System.out.println(i);
    }

    private char[][] arr;
    private int m;
    private int n;
    private int max;
    private int count;

    public int largestArea(String[] grid) {
        m = grid.length;
        n = grid[0].length();
        arr = new char[m][n];
        for (int i = 0; i < m; i++) {
            arr[i] = grid[i].toCharArray();
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (arr[i][j] == '0' || arr[i][j] == '6') {
                    continue;
                }
                if (i == 0 || i == m - 1 || j == 0 || j == n - 1
                        || arr[i - 1][j] == '0' || arr[i + 1][j] == '0' || arr[i][j - 1] == '0' || arr[i][j + 1] == '0') {
                    change(i, j, arr[i][j]);
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (arr[i][j] != '0' && arr[i][j] != '6') {
                    find(i, j, arr[i][j]);
                    max = Math.max(max, count);
                    count = 0;
                }
            }
        }
        return max;
    }

    private void find(int x, int y, char last) {
        if (x < 0 || x == m || y < 0 || y == n) {
            return;
        }
        if (arr[x][y] != last) {
            return;
        }
        arr[x][y] = '0';
        count++;
        find(x - 1, y, last);
        find(x + 1, y, last);
        find(x, y - 1, last);
        find(x, y + 1, last);
    }

    private void change(int x, int y, char last) {
        if (x < 0 || x == m || y < 0 || y == n) {
            return;
        }
        if (arr[x][y] != last) {
            return;
        }
        arr[x][y] = '6';
        change(x - 1, y, last);
        change(x + 1, y, last);
        change(x, y - 1, last);
        change(x, y + 1, last);
    }

}
